package com.alkaid.novel.service.impl;

import com.alkaid.commons.entity.Novel;
import com.alkaid.commons.entity.NovelDetails;
import com.alkaid.commons.ex.DataNotFoundException;
import com.alkaid.novel.mapper.NovelDetailsMapper;
import com.alkaid.novel.mapper.NovelMapper;
import com.alkaid.novel.service.NovelDetailsService;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.alkaid.commons.msg.DataTypeEnum.NOVEL;
import static com.alkaid.commons.msg.DataTypeEnum.NOVEL_DETAIL;

/**
 * @author Kylin
 */
@Service
public class NovelDetailsServiceImpl implements NovelDetailsService {

    private final NovelMapper novelMapper;

    private final NovelDetailsMapper novelDetailsMapper;

    public NovelDetailsServiceImpl(NovelMapper novelMapper, NovelDetailsMapper novelDetailsMapper) {
        this.novelMapper = novelMapper;
        this.novelDetailsMapper = novelDetailsMapper;
    }

    @Override
    public String getSource(Long id) throws DataNotFoundException {
        String text = novelDetailsMapper.findSource(id);
        if (text == null) {
            throw new DataNotFoundException(NOVEL);
        }
        return text;
    }

    @Override
    public Novel getNovelWithDetailsByDetailId(Integer id) throws DataNotFoundException {
        List<NovelDetails> novelDetails = novelDetailsMapper.findSameNovelIdById(id);
        if (novelDetails.size() == 0) {
            throw new DataNotFoundException(NOVEL);
        }
        Integer novelId = novelDetails.get(0).getNovelId();
        Novel novel = novelMapper.selectById(novelId);
        if (novel == null) {
            throw new DataNotFoundException(NOVEL_DETAIL);
        }
        novel.setAuthor(novelDetailsMapper.findAuthors(novelId));
        novel.setNovelDetails(novelDetails);
        return novel;
    }
}
